package com.znxs.bs_c.config.interceptor;

import cn.hutool.core.annotation.Alias;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.znxs.bs_c.common.Status;
import com.znxs.bs_c.entity.User;
import com.znxs.bs_c.exception.ServiceException;
import com.znxs.bs_c.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.jar.JarException;

@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Autowired
    private UserServiceImpl userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 如果不是一个方法直接通过
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        // 空字符串
        if (StrUtil.isBlank(token)){
            throw new ServiceException(Status.InsufficientPermissions.getCode(),"无token 请重新登录");
        }
        // 获取token 中的数据
        String userid;
        try {
            userid = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j){
            throw new ServiceException(Status.InsufficientPermissions.getCode(),"token验证失败，请重新登录");
        }
        // 根据userid 查询数据
        User user = userService.getById(userid);
        if (user == null){
            throw new ServiceException(Status.InsufficientPermissions.getCode(),"用户不存在，请重新登录");
        }
        // 通过用户密码加签验证 验证token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            throw new ServiceException(Status.InsufficientPermissions.getCode(),"token验证失败，请重新登录");
        }
        return true;
    }
}
